define(
	[
		'require',
		'../../service/js/cytoscape.js',
		'../../service/js/cytoscape-cose-bilkent.js',
		'./detail_nodedetail_track_ctrl'
	],
	function(require,cytoscape,regCose){
		regCose( cytoscape );
		var Controller = require('./detail_nodedetail_track_ctrl').extend({
			trackTitle: "慢交易",

			requireAlerts: function(params) {
				var ctrl = this,
					serviceId = ctrl.serviceId(),
					channelValue = this.get("channelValue"),
					typeValue = this.get("typeValue"),
					nodeId = ctrl.get("business").id,
					isTrue = ctrl.get("isTrue");

				var startDate = this.get("startDate"),
					endDate = this.get("endDate");

				if (isLocalDebugModel) {
					endDate = new Date(2014, 9, 1, 12, 0, 0);
					startDate = new Date(+endDate)
					startDate.setHours(startDate.getHours() - 1);
				}
				if(typeValue == "交易类型"){
					typeValue = '';
				}
				if(channelValue == '交易渠道'){
					channelValue = '';
				}

				var params = {
					"appId": ctrl.get("business.id"),
					"keyWord": this.get("keyWord"),
					"startDate": +startDate,
					"pageIndex": this.get("pageIndex"),
					"pageSize": this.get("pageSize"),
					"endDate": +endDate,
					"transactionChannel": channelValue,
					"transactionType": typeValue,
					"orderBy": this.get("orderBy"),
					"desc": this.get("desc")
				};
				//开发调试模式参数
				if (isLocalDebugModel) {
					params = undefined;
				}

				return ctrl.store.ajax("GET", "trades/slow/trade/tracking", params)
					.then(function(response) {
						var status = response.status;
						if (status != "success") {
							return
						};

						ctrl.set('isData', false);

						var alerts = response.result;
						alerts.forEach(function(node, index) {
							node.sequence = index + 1;
							if (node.isError) {
								node.result = "失败";
							} else {
								node.result = "成功";
							}
						});

						if (alerts.length == 0) {
							ctrl.set("pageIndex",0);
							ctrl.set("pageSize",10);
							ctrl.set("totalRows",0);
							ctrl.set("pageCount",0);
						} else {
							ctrl.set("pageIndex",response.meta.pageIndex);
							ctrl.set("pageSize",response.meta.pageSize == 0?10:response.meta.pageSize);
							ctrl.set("totalRows",response.meta.total);
							ctrl.set("pageCount",response.meta.totalPage);
						}

						ctrl.set("alerts", alerts);
						return response;
					});
			},

			topoData: function(initialData) {
				var oElementHas = {};
				var topoElements = {
					nodes: [],
					edges: []
				};
				var resTimes = 0;
				initialData.forEach(function(item) {
					resTimes += item.responseTime;
				});

				initialData.forEach(function(item) {
					var timePer = ((item.responseTime / resTimes) * 100).toFixed(2);
					//edges
					topoElements.edges.push({
						data: {
							id: item.srcIp + item.dstIp,
							source: item.srcIp,
							target: item.dstIp,
							name: item.responseTime + 'ms\n' + timePer + '%\n' + item.typeName
						}
					});

					if (!oElementHas[item.srcIp]) {
						topoElements.nodes.push({
							data: {
								id: item.srcIp,
								name: 'client',
								icon: 'apps/business/img/client.png'
							}
						});
						oElementHas[item.srcIp] = item.srcIp;
					}

					if (!oElementHas[item.dstIp]) {
						topoElements.nodes.push({
							data: {
								id: item.dstIp,
								name: item.serviceTypeName,
								icon: item.serviceIconUrl
							}
						});
						oElementHas[item.dstIp] = item.dstIp;
					}
				});

				return topoElements;
			},

			slowTopo: function(container, data) {
				var cy = cytoscape({
					container: document.getElementById(container),

					elements: data,

					style: [{
						selector: 'node',
						style: {
							'width': 44,
							'height': 44,
							'background-opacity': 0,
							'label': 'data(name)',
							'color': '#ffffff',
							'font-size': '12px',
							'background-image': 'data(icon)'
						}
					}, {
						selector: 'edge',
						style: {
							'width': 1,
							'line-color': '#ffffff',
							'color': '#ffffff',
							'target-arrow-color': '#ccc',
							'target-arrow-shape': 'triangle',
							'curve-style': 'bezier',
							'label': 'data(name)',
							'font-size': '12px',
							'text-wrap': 'wrap',
							'text-background-color': '#1d6aa7',
							'text-background-opacity': 1
						}
					}],

					layout: {
				        name: 'circle',

				    },

					minZoom: 0.5,
					maxZoom: 1,
					wheelSensitivity: 0.4
				});
			},
			actions: {
				timePointChange: function(timeRange) {
					this.set("startDate", timeRange.startDate);
					this.set("endDate", timeRange.endDate);

					this.requireAlerts();
				},
				trackCellClicked: function(e, args, view) {
					var oEvent = e || event;
					var ctrl = this,
						row = args.cell.row(),
						column = args.cell.column();
					var params = {
						"appId": ctrl.get("business.id"),
						"keyWord": row.data.code,
						"startDate": +ctrl.get("startDate"),
						"endDate": +ctrl.get("endDate"),
						tracking: true
					};

					clearTimeout(ctrl.get("time"));
					ctrl.store.ajax("GET", "trades/slow/trade/tracking", params)
						.then(function(response) {
							ctrl.set("boolean", false);

							var view = Broada.getView("businessNodeDetailTrackStackDialog");
							var o = view.$();

							o.parent().css({"left":window.screen.width/2-400+"px"});
							o.parent().css({"top":window.screen.height/2-300+"px"});
							ctrl.set("view",o);
							o.parent().removeClass("bounceOutRight animated");
							o.parent().removeClass("bounceInRight animated");
							view.openDialog();
							o.empty()
								.height(400)
								.css({
									'padding': 0
								})
							.prev().find('span')
								.text('交易号：' + params.keyWord)
								.css({
									'margin': '0',
									float: 'none',
									display: 'inline-block'
								});
							var topoData = ctrl.topoData(response.result);
							setTimeout(function(){
								ctrl.slowTopo('businessNodeDetailTrackStackDialog', topoData);
								$('#businessNodeDetailTrackStackDialog').find('canvas').css({
									left: 0
								});
							},600)
							o.parent().addClass("bounceInRight animated");

							o.parent().on("click", function(event) {
								event.stopPropagation();
							});

							var time = setTimeout(function() {
								ctrl.set("boolean", true);
							}, 1000);
						});
					oEvent.cancelBubble = true;
				}
			}

		});

		APM.BusinessDetailNodedetailSlowtradeController = Controller;
		return Controller;
	}
);